<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <div>
          <el-table :data="articleData" style="width: 100%" max-height="640">
            <el-table-column fixed prop="id" label="id" width="50" />
            <el-table-column prop="title" label="标题" width="200" />
            <el-table-column label="内容" width="600">
              <template #default="scope">
                <div class="content-cell" v-html="scope.row.content"></div>
              </template>
            </el-table-column>
            <el-table-column prop="author" label="作者" width="100" />
            <el-table-column prop="update_time" :formatter="formatTime" label="更新时间" width="200" />
            <el-table-column prop="is_active" label="状态" :formatter="isDeletedFormatter" width="200" />
            <el-table-column fixed="right" label="操作" min-width="100">
              <template #default="scope">
                <el-button link type="primary" size="large" @click.prevent="updateArticle(scope.row)">
                  修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="mt-4" style="width: 100%" plain @click="handleAddArticle">
            新增文章
          </el-button>
        </div>
      </el-main>

      <!-- 新增模态框 -->
      <el-dialog v-model="dialogVisible" fullscreen top="40vh" width="70%" draggable>
        <el-form ref="fromRef" :model="form" label-width="auto" :rules="rules" size="large"
          style="padding-top: 20px; max-width: 800px; margin: 0 auto">
          <el-form-item label="标题">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="form.type_id" placeholder="选择类型" :teleported="false">
              <el-option v-for="item in typeLists" :label="item.type_name" :value="item.id" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="form.is_active" size="large" inline-prompt active-text="显示" inactive-text="隐藏" />
          </el-form-item>

          <div style="display: flex; justify-content: center">
            <el-form-item>
              <TextEditor v-model="form.content" :key="editorKey" />
            </el-form-item>
          </div>
          <div class="dialog-footer" style="display: flex; justify-content: center; ">
            <el-form-item>
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addSubmit"> 提交 </el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </el-container>
  </div>
</template>
<script setup>
import TextEditor from "./components/textEditor.vue";

import { ref, onMounted } from "vue";
import requestUtil from "../../../utils/request";
import dayjs from "dayjs";
import qs from "qs";

// 新增类型列表加载方法
const getTypes = async () => {
  try {
    let result = await requestUtil.post(
      "articleType/select?",
      qs.stringify({
        is_active: "1",
      })
    );
    const data = result.data;
    if (data.code === 200) {
      typeLists.value = data.types;
      // 设置默认选中第一个
      if (data.types.length === 0) {
        form.value.type_id = -1;
      } else {
        form.value.type_id = data.types[0].id;
      }
    } else {
      ElMessage.error("数据加载失败:" + data.info);
    }
  } catch (error) {
    ElMessage.error("请求失败:" + error.message);
  }
};
// 获取文章类型列表
const getArticleList = async () => {
  try {
    let result = await requestUtil.post(
      "article/selectAll?",
      qs.stringify({
        id:"-1"
      })
    );
    const data = result.data;
    if (data.code === 200) {
      articleData.value = data.articleList;
    } else {
      ElMessage.error("数据加载失败:" + data.info);
    }
  } catch (error) {
    ElMessage.error("请求失败:" + error.message);
  }
};
const typeLists = ref([]);
//新增模态框

//新增模态框数据
const fromRef = ref(null);
// 获取当前用户信息
const User = JSON.parse(sessionStorage.getItem("currentUser"));
// 新增模态框form
const form = ref({
  id: "-1",
  title: "",
  content: "",
  type_id: "",
  author: "",
  create_time: "",
  is_active: true
});
// 表单检测
const rules = ref({
  title: [{ required: true, message: "不能为空", trigger: "blur" }],
  content: [{ required: true, message: "不能为空", trigger: "blur" }],
  type_id: [{ required: true, message: "不能为空", trigger: "blur" }],
});
// 深度重置表单数据
const handleDialogClosed = () => {
  fromRef.value.resetFields();
  form.value = {
    id: "",
    title: "",
    content: "",
    type_id: typeLists.value[0]?.id || "",
    is_active: true,
    author: User.username,
  };
};



// 新增文章按钮点击处理
const handleAddArticle = () => {
  dialogVisible.value = true;
  handleDialogClosed(); // 打开对话框时重置表单
};
//新增提交事件 
const addSubmit = () => {
  fromRef.value.validate(async (valid) => {
    form.value.author = User.username; // 设置作者为当前用户
    if (valid) {
      let result = await requestUtil.post(
        "article/addArticle?",
        qs.stringify(form.value)
      );
      let data = result.data;
      if (data.code == 200) {
        articleData.value = data.articleList;
        dialogVisible.value = false;
        ElMessage.success(data.info);

        // 强制重新渲染编辑器
        editorKey.value++; // 修改 key 值使组件重新创建
        // 重置表单
        handleDialogClosed();
        // 重新获取最新数据
        getArticleList();

      } else {
        ElMessage.error(data.info);
      }
    }
  });
};

// 状态转换方法
const isDeletedFormatter = (row) => {
  return row.is_active === true ? "启用" : "不启用";
};
// 统一时间格式化方法
const formatTime = (row, column, cellValue) => {
  return dayjs(cellValue).format("YYYY-MM-DD HH:mm:ss");
};


//修改数据
const updateArticle = async (row) => {
  try {
    let result = await requestUtil.post(
      "article/selectAll?",
      qs.stringify({
        id: row.id,
        is_active: row.is_active,
        title: row.title
      })
    );
    const data = result.data;
    if (data.code === 200) {
      const article = data.articleList[0]
      form.value = {
        id: article.id,
        title: article.title,
        content: article.content,
        type_id: Number(article.type_id),
        is_active: article.is_active,
      };
      dialogVisible.value = true;
    } else {
      ElMessage.error("数据加载失败:" + data.info);
    }
  } catch (error) {
    ElMessage.error("请求失败:" + error.message);
  }
};


const dialogVisible = ref(false);

// 文章列表数据
const articleData = ref([]);

// 页面加载时加载类型列表
onMounted(() => {
  getTypes();
  getArticleList();
});
</script>
<style scoped></style>